<template>
  <el-upload
    ref="refUpload"
    v-model="fileUrl"
    class="nw-upload"
    :name="name"
    :accept="accept"
    :action="action"
    :limit="limit"
    :file-list="fileList"
    :headers="uploadHeaders"
    :before-upload="beforeUpload"
    :on-remove="handleRemove"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :="$attrs"
  >
    <slot />
  </el-upload>
</template>

<script setup>
import { getUmsToken } from '@/utils/cookies'

const props = defineProps({
  name: {
    type: String,
    default: 'file'
  },
  accept: {
    type: String,
    default: '.xlsx,.xls'
  },
  action: {
    type: String,
    default: ''
  },
  limit: {
    type: Number,
    default: 1
  },
  maxSize: {
    type: Number,
    default: 1024 * 1024 * 20
  },
  fileList: {
    type: Array,
    default: () => []
  },
  onRemove: {
    type: Function,
    default: () => {}
  },
  onSuccess: {
    type: Function,
    default: () => {}
  }
})

const emit = defineEmits([
  'on-remove',
  'on-success',
  'before-upload',
  'on-error'
])

const refUpload = ref(null)
const fileUrl = ref('')
const uploadHeaders = {
  Authorization: 'Bearer ' + getUmsToken(),
  lang: g_https.headersLang(),
  timeout: 10000
}

const beforeUpload = file => {
  let isFile = false
  if (!props.accept || props.accept === '*') {
    isFile = true
  } else {
    isFile = props.accept.split(',').some(item => file.name.includes(item))
  }
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isFile) {
    ElMessage.error(g_t('rule.uploadTip'))
  } else if (!isLt20M) {
    ElMessage.error(g_t('rule.uploadSizeTip'))
  }
  emit('before-upload', isFile && isLt20M)
  return isFile && isLt20M
}

const handleRemove = (file, fileList) => {
  fileUrl.value = null
  emit('on-remove', fileUrl.value)
  props.onRemove(file, fileList)
}

const handleExceed = (files, fileList) => {
  ElMessage.warning(g_t('order.uploadNumLargeTips'))
}

const handleSuccess = res => {
  if (res.code === '200') {
    nextTick(() => {
      fileUrl.value = res.data
      emit('on-success', fileUrl.value)
      props.onSuccess(fileUrl.value)
    })
  } else {
    refUpload.value.clearFiles()
    ElMessage({
      message: res.message,
      type: 'error'
    })
    emit('on-error', res)
  }
}
</script>
